package com.kaibes.web.util;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.kaibes.core.base.util.FileUtils;
import com.kaibes.core.spring.ApplicationUtils;
import com.kaibes.web.util.model.PageParam;

public class WebUtils extends org.springframework.web.util.WebUtils {

    public static void shutDown() {
        Thread thread = new Thread(WebUtils::performShutdown);
        thread.setContextClassLoader(WebUtils.class.getClassLoader());
        thread.start();
    }
    
    private static void performShutdown() {
        ApplicationUtils.getInstance().close(500L);
    }
    
    public static String getUrl() {
        HttpServletRequest request = getRequest();
        if (request.getQueryString() != null) {
            return request.getRequestURL().append("?").append(request.getQueryString()).toString();
        } else {
            return request.getRequestURL().toString();
        }
    }
    
    public static String getUri() {
        HttpServletRequest request = getRequest();
        if (request.getQueryString() != null) {
            return new StringBuilder().append(request.getRequestURI()).append("?").append(request.getQueryString()).toString();
        } else {
            return request.getRequestURI();
        }
    }
    
    public static String getHead() {
        HttpServletRequest request = getRequest();
        StringBuilder sb = new StringBuilder();
        sb.append(request.getScheme()).append("://").append(request.getServerName());
        if (request.getServerPort() != 80) {
            sb.append(":").append(request.getServerPort());
        }
        return sb.toString();
    }
    
    public static String getServer() {
        return getRequest().getServerName();
    }
    
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
    
    public static HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }
    
    @SuppressWarnings("unchecked")
	public static <T> T getAttribute(String name) {
    	HttpServletRequest request = getRequest();
    	return (T) request.getAttribute(name);
    }
    
    public static PageParam getPage(int size, int page, String search) {
        HttpServletRequest request = getRequest();
        String _size = request.getParameter("size");
        String _page = request.getParameter("page");
        String _search = request.getParameter("search");
        if (_size != null) {
            size = Integer.parseInt(_size);
        }
        if (_page != null) {
            page = Integer.parseInt(_page);
        }
        if (_search != null) {
            search = _search;
        }
        PageParam p = new PageParam();
        p.setPage(page);
        p.setSize(size);
        p.setSearch(search);
        return p;
    }
    
    public static boolean downFile(File file) {
    	return downFile(file, file.getName());
    }
    
    public static boolean downFile(File file, String filename) {
    	HttpServletRequest request = getRequest();
    	HttpServletResponse response = getResponse();
        if (file.exists()) {
            String rangeString = request.getHeader("Range");// 如果是video标签发起的请求就不会为null

            long contentLength = file.length();
            long start = 0L;
            if (rangeString != null) {
                long fileLength = contentLength;
                response.reset();
                response.setHeader("Accept-Ranges", "bytes");
                response.setStatus(javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT);

                String rangBytes = rangeString.replaceAll("bytes=", "");
                start = Long.parseLong(rangBytes.substring(0, rangBytes.indexOf("-")));
                if (rangBytes.endsWith("-")) { // bytes=270000-
                    contentLength = fileLength - start; // 客户端请求的是270000之后的字节（包括bytes下标索引为270000的字节）
                } else { // bytes=270000-320000
                    Long end = Long.parseLong(rangBytes.substring(rangBytes.indexOf("-") + 1, rangBytes.length()));
                    contentLength = end - start; // 客户端请求的是 270000-320000 之间的字节
                    if (contentLength > fileLength) {
                        contentLength = fileLength;
                    }
                }
                response.setContentLengthLong(contentLength);

                StringBuilder sb = new StringBuilder();
                sb.append("bytes ").append(start).append("-").append(start + contentLength - 1).append("/")
                        .append(fileLength);
                response.setHeader("Content-Range", sb.toString());

                response.setContentType("application/octet-stream");
                response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            }

            try {
				boolean flag = FileUtils.transferTo(file, response.getOutputStream(), start);
				if (flag) {
					return true;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
        return false;
    }

}
